const RoleModel = require("../model/RoleModel")
const RoleServices = require("../services/RoleServices")
const RoleSchema = require("../schema/RoleSchema")
const { validate, errorResponese, successResponese } = require("../utils/validate")
const { filterQuery, handleReg} = require("../utils/tools")
const RoleController = {
    find: async (req, res) => {
        const { pages, params } = filterQuery(req.query)
        const data = await RoleServices.find(handleReg(req.query,["rolename","status","createTime","describe"]), pages)
        // 根据查询条件获取数据总条目
        let total = await RoleModel.count(params)
        res.send({
            code: "200",
            msg: "角色查询成功",
            total,
            data,
        })
    },
    append: async (req, res) => {
        const v = await validate(RoleSchema.append, req.body)
        if (v) return errorResponese({ res: res, msg: v })

        // 判断新增的角色名是否重复
        const data = await RoleServices.find({ rolename: req.body.rolename })

        if (data.length !== 0) return errorResponese({
            res: res,
            code: "400",
            msg: "角色名称重复"
        })

        let result = await RoleServices.append(req.body)

        if (result) return successResponese({
            res: res,
            msg: "角色创建成功!"
        })

        errorResponese({
            res: res,
            msg: "角色创建失败"
        })
    },
    update: async (req, res) => {

        if(mongoose.Types.ObjectId("64083b4cc94e5ceabacb4b52") === req.body._id) {
            return  errorResponese({
                res: res,
                msg: "管理员角色不允许修改!"
            })
        }

        if (req.body.type === "sort") {
            return RoleController.sort(req,res)
        }

        const v = await validate(RoleSchema.update, req.body)
        if (v) return errorResponese({ res: res, msg: v })

        let result = await RoleServices.update(req.body)
        if (result) return successResponese({
            res: res,
            msg: "角色修改成功!"
        })

        errorResponese({
            res: res,
            msg: "角色修改失败"
        })
    },
    remove: async (req, res) => {
        let result = await RoleServices.remove(req.params.id)
        if (result) return successResponese({
            res: res,
            msg: "角色删除成功!"
        })

        errorResponese({
            res: res,
            msg: "角色删除失败"
        })
    },
    sort: async (req, res) => { 
        for (let i = 0; i < req.body.data.length; i++) {
            const item = req.body.data[i];
            await RoleServices.update(item).then().catch(error => {
                errorResponese({
                    res: res,
                    msg: `用户${item._id}排序失败`
                })
            })
        }
        successResponese({
            res: res,
            msg: "用户修改成功"
        })
    },
}

module.exports = RoleController